<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>新增送货地址</p>
    </header>
    
    <!-- 表单部分 -->
    <ul class="form-box">
      <li>
        <div class="title">
          联系人：
        </div>
        <div class="content">
          <input type="text" v-model="deliveryAddress.contactName" placeholder="联系人姓名">
        </div>
      </li>
      <li>
        <div class="title">
          性别：
        </div>
        <div class="content" style="font-size: 3vw;">
          <input type="radio" v-model="deliveryAddress.contactSex" value="1" style="width:6vw;height:3.2vw;">男
          <input type="radio" v-model="deliveryAddress.contactSex" value="0" style="width:6vw;height:3.2vw;">女
        </div>
      </li>
      <li>
        <div class="title">
          电话：
        </div>
        <div class="content">
          <input type="tel" v-model="deliveryAddress.contactTel" placeholder="电话">
        </div>
      </li>
      <li>
        <div class="title">
          收货地址：
        </div>
        <div class="content">
          <input type="text" v-model="deliveryAddress.address" placeholder="收货地址">
        </div>
      </li>
    </ul>
    
    <div class="button-add">
      <button @click="addUserAddress" :disabled="isSaving">
        {{ isSaving ? '保存中...' : '保存' }}
      </button>
    </div>
    
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'AddUserAddress',
  data() {
    return {
      businessId: this.$route.query.businessId,
      user: {},
      deliveryAddress: {
        contactName: '',
        contactSex: 1,
        contactTel: '',
        address: '',
        customer: {
          id: null,
          username: ''
        }
      },
      isSaving: false
    }
  },
  created() {
    this.user = this.$getSessionStorage('user');
    if (!this.user?.userId) {
      this.$router.push('/login');
      return;
    }
    
    // 设置用户信息
    this.deliveryAddress.customer.id = this.user.userId;
    this.deliveryAddress.customer.username = this.user.username;
  },
  components: {
    Footer
  },
  methods: {
    validateForm() {
      if (!this.deliveryAddress.contactName.trim()) {
        alert('联系人姓名不能为空！');
        return false;
      }
      
      if (!this.deliveryAddress.contactTel.trim()) {
        alert('联系人电话不能为空！');
        return false;
      }
      
      // 简单的电话号码验证
      if (!/^1[3-9]\d{9}$/.test(this.deliveryAddress.contactTel)) {
        alert('请输入正确的手机号码！');
        return false;
      }
      
      if (!this.deliveryAddress.address.trim()) {
        alert('收货地址不能为空！');
        return false;
      }
      
      return true;
    },
    
    async addUserAddress() {
      if (!this.validateForm()) return;
      
      this.isSaving = true;
      
      try {
        const response = await this.$axios.post('/api/addresses', this.deliveryAddress, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        if (response.data.success) {
          alert('地址添加成功');
          this.$router.push({
            path: '/userAddress',
            query: {
              businessId: this.businessId
            }
          });
        } else {
          alert('新增地址失败: ' + (response.data.message || ''));
        }
      } catch (error) {
        console.error('新增地址失败:', error);
        this.handleApiError(error);
      } finally {
        this.isSaving = false;
      }
    },
    
    handleApiError(error) {
      if (error.response) {
        // 请求已发出，服务器返回状态码不在2xx范围
        switch (error.response.status) {
          case 400:
            alert('请求参数错误: ' + (error.response.data.message || ''));
            break;
          case 401:
            alert('用户未授权，请重新登录');
            this.$router.push('/login');
            break;
          case 500:
            alert('服务器内部错误，请稍后再试');
            break;
          default:
            alert('请求失败: ' + (error.response.data.message || ''));
        }
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        alert('网络错误，请检查您的网络连接');
      } else {
        // 其他错误
        alert('请求配置错误: ' + error.message);
      }
    }
  }
}
</script>

<style scoped>
  /*************** 总容器 ***************/
  .wrapper {
    width: 100%;
    height: 100%;
    background-color: #F5F5F5;
  }

  /*************** header ***************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    display: flex;
    justify-content: space-around;
    align-items: center;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    /*保证在最上层*/
    z-index: 1000;
  }

  /*************** （表单信息） ***************/
  .wrapper .form-box {
    width: 100%;
    margin-top: 12vw;
    background-color: #fff;
  }

  .wrapper .form-box li {
    box-sizing: border-box;
    padding: 4vw 3vw;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
  }

  .wrapper .form-box li .title {
    flex: 0 0 18vw;
    font-size: 3.8vw;
    font-weight: 700;
    color: #666;
  }

  .wrapper .form-box li .content {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .wrapper .form-box li .content input[type="text"],
  .wrapper .form-box li .content input[type="tel"] {
    border: none;
    outline: none;
    width: 100%;
    height: 8vw;
    font-size: 3.8vw;
    padding: 0;
  }

  .wrapper .form-box li .content input[type="radio"] {
    margin-right: 2vw;
    margin-left: 4vw;
  }

  .wrapper .button-add {
    box-sizing: border-box;
    padding: 6vw 3vw;
    margin-top: 4vw;
  }

  .wrapper .button-add button {
    width: 100%;
    height: 12vw;
    font-size: 4.2vw;
    font-weight: 700;
    border: none;
    outline: none;
    border-radius: 6px;
    color: #fff;
    background-color: #38CA73;
    transition: background-color 0.3s;
  }

  .wrapper .button-add button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
  }

  .wrapper .button-add button:hover:not(:disabled) {
    background-color: #2db863;
  }
</style>